<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            * {
                padding: 0;
                margin: 0;
                user-select: none;
            }

            html, body {
                height: 100%;
                min-height: 600px;
            }

            #box {
                height: 100%;
                position: relative;
            }

            img {
                vertical-align: top;
                width: 100px;
                height: 100px;
            }


            #plane {
                position: absolute;
                bottom: 0;
                left: 0;
            }

            .bullet {
                position: absolute;
                width: 6px;
                height: 18px;
                background: red;
                top: calc(100% - 100px);
            }

        </style>
    </head>
    <body>

        <div id="box">
            <img id="plane" src="plane.png" alt="">
        </div>
        
    </body>
</html>
<script>
    // 小飞机
    var plane = document.getElementById('plane');

    // boxDiv
    var boxDiv = document.getElementById('box');

    // 飞机的宽度
    var width = 100;

    // 飞机移动的最大宽度
    var max = boxDiv.clientWidth - width;

    var left = 0;

    var bulletsArray = [];

    var bulletTimerId = null;


    // 鼠标按下事件
    document.onmousedown = function(e) {
        
        bulletTimerId = setInterval(function() {

            bit();

        }, 100);

        // 鼠标移动事件
        document.onmousemove = function(e) {
            
            // 获取鼠标的位置
            var x = e.clientX;
        

            if (x - 50 >= 0 && x - 50 <= max) {
                left = x - 50;
            } else if (x - 50 < 0) {
                left = 0;
            } else {
                left = max;
            }

            plane.style.left = left + 'px';
            
        };

        document.onmouseup = function() {
            document.onmousemove = null;
            clearInterval(bulletTimerId);
        };


    };


    // 发射子弹
    function bit() {

        // 创建子弹
        var bullet = document.createElement('div');
        bullet.className = "bullet";
        bullet.style.left = left + 50 - 3 + "px";
        bullet.top = boxDiv.clientHeight - 100;
        boxDiv.appendChild(bullet);

        // 子弹下标
        bullet.index = bulletsArray.length;
        bulletsArray.push(bullet);
        bullet.timerId = setInterval(function() {
            console.log(bullet.index);
            bullet.top -= 18;
            bullet.style.top = bullet.top + 'px';

            if (bullet.top <= -18) {
                clearInterval(bullet.timerId);
                bulletsArray.splice(bullet.index, 1);
                bullet.remove();
            }

        }, 20);

    }










</script>


